#include "dbhelper.h"

#include <ctime>

using std::vector;

DbHelper::DbHelper()
{
    this->db = new DbWorker();
    this->main_select = "Select Rodove.id as id, Rodove.name as name, Rodove.place, Rodove.skhema, Rodove.year_start, Rodove.year_used, Oblast.name as oblast, Region.name as region, RodoweSizeGas.name as gas_size, RodoweSizeOil.name as oil_size, RodoweType.name as rodowe_type from Rodove left join Oblast on Oblast.id =Rodove.oblast_id left  join Region on Region.id =Rodove.region_id left join RodoweSizeGas on RodoweSizeGas.id =Rodove.oil_size_id left join RodoweSizeOil on RodoweSizeOil.id =Rodove.gas_size_id left join RodoweType on RodoweType.id = Rodove.type_id";

}

//private
vector<Rodove> DbHelper::getResult(string query){
   vector<vector<string> > res = this->db->select(query);

    vector<Rodove> arr;
    arr = this->convertResultToRodove(res);
    return arr;
}

vector<Rodove> DbHelper::convertResultToRodove(vector<vector<string> > res){
    vector<Rodove> arr;

    for(vector<vector<string> >::iterator it = res.begin(); it < res.end(); ++it)
    {
            vector<string> row = *it;


            Rodove *item = new Rodove();

            int id_int;
            std::stringstream id(row.at(0));
            id>>id_int;

            int year_start_int;
            std::stringstream year_start(row.at(4));
            year_start>>year_start_int;

            int year_used_int;
            std::stringstream year_used(row.at(5));
            year_used>>year_used_int;



            item->setId(id_int);     //id
            item->setName(row.at(1));   //name
            item->setPlace(row.at(2));  //place
            item->setSkhema(row.at(3)); //skhema
            item->setYear_start(year_start_int); //year_start
            item->setYear_used(year_used_int);  //year_used
            item->setOblast(row.at(6)); //oblast
            item->setRegion(row.at(7)); //region
            item->setGas_size(row.at(8));   //gas size
            item->setOil_size(row.at(9));   //oil size
            item->setType(row.at(10));   //type

            arr.push_back(*item);
    }

    return arr;
}

//public
vector<Rodove> DbHelper::select()
{
    string query = this->main_select;
    return this->getResult(query);
}


vector<Rodove> DbHelper::selectYearAfter(int year){
    time_t rawtime;
    struct tm * timeinfo;

    time ( &rawtime );
    timeinfo = localtime ( &rawtime );


    int cur_year = timeinfo->tm_year + 1900;

    //convert years
    std::stringstream cur_year_str;
    cur_year_str<<cur_year;

    std::stringstream need_year_str;
    need_year_str<<year;

    string query = this->main_select;
    query.append(" WHERE " + cur_year_str.str() + "-year_start" + "<" + need_year_str.str());

    return this->getResult(query);

}




